package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
	"goserver/internal/config"
	"goserver/internal/db"
	"goserver/internal/handler"
	"goserver/internal/middleware"
	"goserver/internal/model"
	"goserver/internal/service"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"goserver/internal/logger"
	"goserver/internal/alert"
)

// @title WorkTool API
// @version 1.0.0
// @description WorkTool API文档
// @contact.name Admin
// @contact.email admin@example.com
// @host localhost:8080
// @BasePath /api
// @securityDefinitions.apikey Bearer
// @in header
// @name Authorization

func main() {
	// 1. 解析命令行参数
	configFile := flag.String("config", "config/config.yaml", "配置文件路径")
	flag.Parse()

	// 2. 加载配置
	if err := config.LoadConfig(*configFile); err != nil {
		log.Fatalf("加载配置失败: %v", err)
	}

	// 2.1 初始化日志系统
	if err := logger.InitLogger(config.GlobalConfig.Log.Dir, config.GlobalConfig.Log.Level); err != nil {
		log.Fatalf("初始化日志系统失败: %v", err)
	}

	// 2.2 初始化告警系统
	alert.InitAlertManager(config.GlobalConfig.Alert)

	// 3. 初始化数据库连接
	if err := db.InitDB(); err != nil {
		log.Fatalf("初始化MySQL失败: %v", err)
	}
	defer db.Close()

	if err := db.InitRedis(); err != nil {
		log.Fatalf("初始化Redis失败: %v", err)
	}

	// 4. 初始化模型
	messageModel := model.NewMessageModel(db.DB, db.Redis)
	userModel := model.NewUserModel(db.DB)
	robotCodeModel := model.NewRobotCodeModel(db.DB)

	// 5. 初始化服务
	deviceService := service.NewDeviceService(db.DB)
	tokenService := service.NewTokenService(db.DB)
	userService := service.NewUserService(userModel)
	authService := service.NewAuthService(userModel, tokenService)
	robotCodeService := service.NewRobotCodeService(robotCodeModel)
	statsService := service.NewStatsService(db.DB)

	// 6. 初始化处理器
	authHandler := handler.NewAuthHandler(authService)
	userHandler := handler.NewUserHandler(userService)
	robotCodeHandler := handler.NewRobotCodeHandler(robotCodeService)
	statsHandler := handler.NewStatsHandler(statsService)
	
	// 7. 初始化中间件
	authMiddleware := middleware.NewAuthMiddleware(tokenService)

	// 8. 设置路由
	gin.SetMode(gin.ReleaseMode)
	router := gin.Default()
	
	// 添加中间件
	router.Use(gin.Recovery())
	router.Use(middleware.LoggerMiddleware())
	router.Use(middleware.CORS())
	router.Use(middleware.Metrics())

	// 创建性能指标收集器
	metricsCollector := middleware.NewMetricsCollector()

	// 添加性能监控中间件
	router.Use(metricsCollector.Profiler())

	// 注册性能监控路由
	metricsHandler := handler.NewMetricsHandler(metricsCollector)
	metricsHandler.RegisterRoutes(router)

	// 控制指标路由
	router.GET("/metrics", gin.WrapH(promhttp.Handler()))

	// 设置路由
	h := handler.NewRouter(
		deviceService,
		messageModel,
		authHandler,
		
		authMiddleware,
		robotCodeHandler,
		userHandler,
		statsHandler,
	)
	h.SetupRoutes(router)

	// 9. 启动服务器
	srv := &http.Server{
		Addr:           fmt.Sprintf(":%d", config.GlobalConfig.Server.Port),
		Handler:        router,
		ReadTimeout:    time.Duration(config.GlobalConfig.Server.ReadTimeout) * time.Second,
		WriteTimeout:   time.Duration(config.GlobalConfig.Server.WriteTimeout) * time.Second,
		MaxHeaderBytes: config.GlobalConfig.Server.MaxHeaderBytes,
	}

	// 启动服务器
	go func() {
		log.Printf("服务器启动在 %s\n", srv.Addr)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("启动服务失败: %v", err)
		}
	}()

	// 等待中断信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("正在关闭服务器...")

	// 优雅关闭
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("服务器关闭:", err)
	}

	log.Println("服务器已关闭")
}
